package register

import (
	"fmt"
	"github.com/hashicorp/consul/api"
	"go.uber.org/zap"
)

type Registry interface {
	ConsulRegister(Address string, Port int, name string, tags []string, id string) error
	CounsulDregister(ServerId string)
}
type Register struct {
	Address string
	Port    int
}

func NewCounsulRegister(address string, port int) *Register {
	return &Register{Address: address, Port: port}
}

func (r *Register) ConsulRegister(address string, port int, name string, tags []string, serverId string) error {

	// ----------------------- 1. 注册consul服务 -----------------------
	// 1、初始化consul配置
	consulConfig := api.DefaultConfig()
	consulAddress := fmt.Sprintf("%s:%d", r.Address, r.Port)
	consulConfig.Address = consulAddress
	// consulConfig.Address = "127.0.0.1:8500"  // consul服务的默认地址可省略，如果不是本机，需要补充
	client, err := api.NewClient(consulConfig)
	if err != nil {
		zap.S().Error("初始化consule失败：", err.Error())
		return err
	}

	//健康检查配置
	//check := &api.AgentServiceCheck{
	//	GRPC:                           "127.0.0.1:8021/health",
	//	Timeout:                        "5s", //超时
	//	Interval:                       "5s", //间隔时间
	//	DeregisterCriticalServiceAfter: "10s",
	//}

	registration := new(api.AgentServiceRegistration)
	registration.Name = name
	//registration.ID = global.ServiceConfig.Name
	registration.ID = serverId
	registration.Address = address
	registration.Port = port
	registration.Tags = tags
	//registration.Check = check //健康检查

	err = client.Agent().ServiceRegister(registration)
	if err != nil {
		zap.S().Error("consul注册失败：", err.Error())
		return err
	}
	return nil
	// ----------------------- 注册consul服务 -----------------------
}

// 注销服务
func (r *Register) CounsulDregister(ServerId string) error {
	consulConfig := api.DefaultConfig()
	// consulConfig.Address = "127.0.0.1:8500"  // consul服务的默认地址可省略，如果不是本机，需要补充
	client, err := api.NewClient(consulConfig)
	if err = client.Agent().ServiceDeregister(ServerId); err != nil {
		zap.S().Error("注销失败")
		return err
	}
	return err

}
